from google.appengine.dist import use_library
use_library('django', '1.2')

from google.appengine.ext import db
from google.appengine.ext.db import polymodel
from datetime import date
import time
import logging

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

class corkBoard():
  def __init__(self, text):
    name = text
  

class postIt(db.Model):
  name = db.StringProperty(required = True)
  text = db.StringProperty(required=True)
  category = db.StringProperty(required=True)
  creationTime= db.IntegerProperty(required = True)

  def archive (self):
    self.category= 'archive'

def createCorkBoard(name):
  logging.info('Created Corkboard')
  return corkBoard(name)

def createPostIt(name, text, category, creationTime):
  if (noSpam (text)):
    p = postIt(name = name, text = text, category = category, creationTime = creationTime)
    p.put()
  else:
    logging.info('OBSCENE WORD')


def noSpam(text):
  obsceneWords= ['shit', 'fuck', 'ass', 'bitch', 'butt', 'damn', 'dick', 'fag', 'gay', 'nig', 'tit', 'whore']
  textSplit= text.split()
  validSticky= True

  for text in textSplit:
    for obscene in obsceneWords: 
      if text.lower().find(obscene) > -1:
        logging.info('Obscene Word!')
        validSticky= False
       
  return validSticky

def getPostIts(category):
  query = postIt.all()
  return query.filter('category =', category)

def displayPostItCat(category):
  logging.info('')
  logging.info('One Category')
  logging.info('Text\tKey')
  for i in getPostIts(category):
    logging.info('%s' %(i.text))

def displayPostIts():
  logging.info('Text\tKey\tCategory\tTime')
  for i in postIt.all():
    logging.info('%s\t%s\t%s' %(i.text, i.category, i.creationTime))

def resetPostIts():
  #print 'Reset PostIts'
  query = postIt.all()
  if query:
    for i in query:
      i.delete()
  #print ''

def searchForText(text):
  searchtext= text.split()
  query= postIt.all()
  searchnotes= []
  counter=0
  
  if query:
    sanitizednotes= []

    for notes in query:
      notessplit= notes.text.split() #one note in list

      for text in searchtext: #iterates thru all the words entered in
        if text.replace('!', '').replace('-', '').replace('(', '').replace(')', '').replace('.', '').replace (',','').replace('?', '').replace(':','').replace(';','').replace('','') in notessplit:
          searchnotes.append(notes) #show the pastnote
          counter +=1
          break
 
  return searchnotes

def searchForAuthor(text):
  query= postIt.all()
  toReturn= []

  if query:
    logging.info ('in searchForAuthor')
    for notes in query:
      logging.info (notes.name.lower())
      if text.lower()== notes.name.lower():
        logging.info ('appending notes')
        toReturn.append (notes)

  return toReturn

def CheckTime():
  query= postIt.all()
  if query:
    end=int(date.today().toordinal())
    for i in query:
      diff = (end - i.creationTime)
      if diff > 10:
        i.archive() 
        
c = createCorkBoard('personal')

class corkBoardHandler(webapp.RequestHandler):
  def get(self):
    logging.info('corkBoardHandler def get')
    logging.info(postIt.all())
    template_values = {'Stickynotes': getPostIts('main')}
    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, template_values))

class SchoolHandler(webapp.RequestHandler):
  def get(self):
    template_values = {'Stickynotes': postIt.all().filter('category =', 'school')}
    path = os.path.join(os.path.dirname(__file__), 'school.html')
    self.response.out.write(template.render(path, template_values))

  def post(self):
    name = self.request.get('name')
    text = self.request.get('message')
    creationTime = date.today().toordinal()
    if name and text:
      if text.find('http://') > -1:
        sticky = createPostIt(name=name, text = text, category = 'school', creationTime = creationTime)
      else:
        sticky = createPostIt(name=name, text = text, category = 'school', creationTime = creationTime)
    self.redirect('/school.html')

class CommunityHandler(webapp.RequestHandler):
  def get(self):
    template_values = {'Stickynotes': postIt.all().filter('category =', 'community')}
    path = os.path.join(os.path.dirname(__file__), 'community.html')
    self.response.out.write(template.render(path, template_values))

  def post(self):
    name = self.request.get('name')
    text = self.request.get('message')
    creationTime = date.today().toordinal()
    if name and text:
      if text.find('http://') > -1:
        sticky = createPostIt(name=name, text = text, category = 'community', creationTime = creationTime)
      else:
        sticky = createPostIt(name=name, text = text, category = 'community', creationTime = creationTime)
    self.redirect('/community.html')

class SearchHandler (webapp.RequestHandler):
  def get(self):
    searchText = self.request.get('message')
    logging.info (searchText)
    allnotes=[]

    if (searchText == ''):
      allnotes.append(postIt(name = 'None', text = 'Please enter a search query', category = 'None', creationTime = 0))
    else:
      Text= self.request.get ('text')
      Author= self.request.get ('author')
      textlist=[]
      authorlist=[]

      if (Text== 'true'):
        textlist= searchForText(searchText)
        logging.info ('textlist')
      if (Author== 'true'):       
        authorlist= searchForAuthor(searchText)
        logging.info('authorlist')

      if (len(textlist) ==0 and len(authorlist)==0):
        allnotes.append(postIt(name = 'None', text = 'No Search Found', category = 'None', creationTime = 0))
      else: 
        allnotes= textlist
        for notes in authorlist:
          allnotes.append(notes)

    template_values= {'Stickynotes': allnotes} 
    path= os.path.join(os.path.dirname(__file__), 'search.html') 
    self.response.out.write(template.render(path, template_values))

class DeveloperHandler(webapp.RequestHandler):
  def get(self):
    template_values = {}
    path = os.path.join(os.path.dirname(__file__), 'developer.html')
    self.response.out.write(template.render(path, template_values))

CheckTime()

def main():
  application = webapp.WSGIApplication([('/', corkBoardHandler),
                                        ('/school.html', SchoolHandler),
                                        ('/community.html', CommunityHandler),
                                        ('/developer.html', DeveloperHandler),
                                        ('/search.*', SearchHandler)],
                                       debug=True)
  run_wsgi_app(application)

if __name__ == '__main__':
  main()
search ('Hello')
